//
//  BannerView.swift
//  DayStudy
//
//  Created by Wheatping on 16/3/7.
//  Copyright © 2016年 Wheatping. All rights reserved.
//

typealias ScrollViewToIndex = (index:Int)->()
typealias ScrollViewSelectIndex = (index:Int)->()


class BannerView: UIView,UIScrollViewDelegate,UIGestureRecognizerDelegate{
    
    var toIndex:ScrollViewToIndex?
    var selectIndex:ScrollViewSelectIndex?

    
    var autoPlayTimeInterval = 5.0 //自动滚动时间默认2.0

    var dataSourceImages:[String]?
    
    private var scrollView = UIScrollView()

    private var pageControl = UIPageControl()
    
    private var currentSelectedPage = 0
    
    private var afterTimer:NSTimer!
    
    
    /**
     初始化方法
     
     - returns:
     */
    func initialize() {
        
        self.clipsToBounds = true
    
        self.initializeScrollView()
        self.initializePageControl()
    }
    
    func initializeScrollView() {
        
        scrollView.frame = CGRectMake(0,0,CGRectGetWidth(self.frame),CGRectGetHeight(self.frame))
        scrollView.delegate = self
        scrollView.pagingEnabled = true
        scrollView.bounces=false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.autoresizingMask = self.autoresizingMask
        scrollView.scrollsToTop = false
        self.addSubview(scrollView)
    }
    
    func initializePageControl() {
        
        pageControl.frame = CGRectMake(0, 0, CGRectGetWidth(scrollView.frame), 30)
        pageControl.center = CGPointMake(CGRectGetWidth(scrollView.frame)*0.5, CGRectGetHeight(scrollView.frame) - 12.0)
        pageControl.numberOfPages = 0
        pageControl.userInteractionEnabled = false
        self.addSubview(pageControl)
        //scrollView.bringSubviewToFront(pageControl)
    }
    
    
    /**
     开始启动Banner自动滚动
     */
    func startRun() {
        
        initialize()
        
        if dataSourceImages == nil || dataSourceImages!.count < 1
        {
            return
        }
        
        if (dataSourceImages!.count == 1)
        {
    
            let imageView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(scrollView.frame), CGRectGetHeight(scrollView.frame)))
            imageView.contentMode = UIViewContentMode.ScaleToFill
            imageView.backgroundColor = UIColor.clearColor()
            imageView.image=PlaceholderImage
            scrollView.addSubview(imageView)
            
            return
        }
        
        pageControl.numberOfPages = dataSourceImages!.count
        pageControl.currentPage = 0

        var copyDataImageSource=Array(count: dataSourceImages!.count+2, repeatedValue: "")
        
        for var i=0; i < copyDataImageSource.count; i++
        {
            if i == 0{
                copyDataImageSource[i]=dataSourceImages![dataSourceImages!.count - 1]
            }else if i == dataSourceImages!.count + 1{
                copyDataImageSource[i]=dataSourceImages![0]
            }else{
                copyDataImageSource[i]=dataSourceImages![i - 1]
            }
        }
        
        dataSourceImages=copyDataImageSource
        
        let contentWidth = CGRectGetWidth(scrollView.frame)
        let contentHeight = CGRectGetHeight(scrollView.frame)

        scrollView.contentSize = CGSizeMake(contentWidth * CGFloat(dataSourceImages!.count), contentHeight)
    
        for var i = 0; i < dataSourceImages!.count; i++ {
    
            let imgRect = CGRectMake(contentWidth * CGFloat(i), 0, contentWidth, contentHeight)
            let imageView = UIImageView(frame: imgRect)
            imageView.backgroundColor = UIColor.clearColor()
            imageView.contentMode = UIViewContentMode.ScaleToFill
            imageView.sd_setImageWithURL(NSURL(string: dataSourceImages![i]), placeholderImage: PlaceholderImage)
            scrollView.addSubview(imageView)
        }
    
        scrollView.contentOffset = CGPointMake(CGRectGetWidth(scrollView.frame), 0)
    
        // single tap gesture recognizer
        let tapGestureRecognize = UITapGestureRecognizer(target: self, action: "singleTapGestureRecognizer:")
        tapGestureRecognize.delegate = self
        tapGestureRecognize.numberOfTapsRequired = 1
        scrollView.addGestureRecognizer(tapGestureRecognize)
        
        afterDelay()
        
    }
    
    /**
     scrollView滚动到指定目标位置
     
     - parameter targetX:  目标X坐标
     - parameter animated: 是否有动画
     */
    func moveToTargetPosition(targetX:CGFloat,animated:Bool) {
        scrollView.setContentOffset(CGPointMake(targetX, 0), animated: animated)
    }
    
    /**
     根据当前页码滚动到下一个页码
     
     - parameter switchPage:    传人页码
     - parameter animated: 是否动画
     - parameter userInterface: 是否是用户滑动
     */
    func setSwitchPage(switchPage:Int,animated:Bool,userInterface:Bool)
    {
        var page = -1
        
        if userInterface
        {
            page = switchPage
        }else
        {
            currentSelectedPage++
            page = currentSelectedPage % (dataSourceImages!.count-1)
        }
        
        if dataSourceImages!.count > 1
        {
            if page >= dataSourceImages!.count - 2
            {
                page = dataSourceImages!.count - 3
                currentSelectedPage = 0
                self.moveToTargetPosition(CGRectGetWidth(scrollView.frame)*CGFloat(page+2), animated: animated)
            }else
            {
                self.moveToTargetPosition(CGRectGetWidth(scrollView.frame)*CGFloat(page+1), animated: animated)
            }
        }else
        {
            self.moveToTargetPosition(0.0, animated: animated)
        }
        
        self.scrollViewDidScroll(scrollView)
    }
    
    
    /**
     计时器自动执行
     */
    func afterDelay() {
    
        afterTimer = NSTimer.scheduledTimerWithTimeInterval(autoPlayTimeInterval, target: self, selector: "autoSwitchBannerView", userInfo: nil, repeats: true)
        
        afterTimer.fireDate=NSDate(timeIntervalSinceNow: autoPlayTimeInterval)
    }
    
    //自动执行的方法
    func autoSwitchBannerView() {
        
        self.setSwitchPage(-1, animated: true, userInterface: false)
        
    }
    
    //UIScrollViewDelegate
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        var targetX = scrollView.contentOffset.x
        
        let item_width = CGRectGetWidth(scrollView.frame)
        
        if dataSourceImages!.count >= 3
        {
            if targetX >= item_width * CGFloat(dataSourceImages!.count - 1)
            {
                targetX = item_width
                scrollView.contentOffset=CGPointMake(targetX, 0)
            }else if targetX <= 0
            {
                targetX = item_width * CGFloat(dataSourceImages!.count - 2)
                scrollView.contentOffset = CGPointMake(targetX, 0)
            }
        }
        
        var page = Int((scrollView.contentOffset.x + item_width * 0.5) / item_width)
        
        if dataSourceImages!.count > 1
        {
            page--
            if page >= pageControl.numberOfPages
            {
                page = 0
            }else if page < 0
            {
                page = pageControl.numberOfPages-1
            }
        }
        
        currentSelectedPage = page
        
        if page != pageControl.currentPage
        {
            if toIndex != nil
            {
                toIndex!(index: page)
            }
        }
        
        pageControl.currentPage = page
    }
    
    //开始拖拽
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        //暂停计时（开始时间给了一个无限期的时间）
        afterTimer.fireDate=NSDate.distantFuture()
        
    }
    
    //结束拖拽
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        //5.0秒后继续计时
        afterTimer.fireDate=NSDate(timeIntervalSinceNow: autoPlayTimeInterval)
    }
    
    //UITapGestureRecognizerSelector
    func singleTapGestureRecognizer(tapGesture:UITapGestureRecognizer) {
    
        let page = Int(scrollView.contentOffset.x) / Int(CGRectGetWidth(scrollView.frame))
    
        if selectIndex != nil
        {
            selectIndex!(index: page-1)
        }
    }
    
}

